package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import tools.OptionReader;
import calendar.CheckboxCalendar;

/**
 * Klasse liefert Möglichkeit Kalender zu bearbeiten
 * 
 * @author Michi
 * 
 */
public class DeleteCalendarsWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8488022247383156074L;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;
	private DefaultListModel dlm;
	private CheckBoxList calendars;
	private Connection connection;
	@SuppressWarnings("unused")
	private Statement stat;
	private LinkedList<CheckboxCalendar> llcalendars = new LinkedList<CheckboxCalendar>();

	// Sprache
	int speak = 1;
	String[] fenstername = { "Kalender Löschen", "Delete Calendar",
			"Calendarium Exstinguere" };
	String[] buttondelete = { "Löschen", "Delete", "Exstinguere" };
	String[] buttoncancel = { "Abbrechen", "Cancel", "Destruere" };
	String[] auswahl = { "Folgende Kalender löschen:",
			"Delete the selected calendars:", "Delete sequenti Calendario:" };

	/**
	 * Konstruktor
	 * 
	 * @param openedfrom
	 *            Instanz dessen, durch welches das Fenster geöffnet wurde
	 */
	public DeleteCalendarsWindow(final Object openedfrom) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);
		speak = Integer.parseInt(or.getLanguage());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle(fenstername[speak]);

		Dimension size = new Dimension(300, 350);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setBackground(new Color(r, g, b));
		getContentPane().setLayout(null);

		JLabel wegdamit = new JLabel();
		wegdamit.setBounds(20, 24, 256, 28);
		wegdamit.setText(auswahl[speak]);
		getContentPane().add(wegdamit);

		dlm = new DefaultListModel();
		calendars = new CheckBoxList();
		calendars.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();

		}

		try {
			ResultSet rscalendars = getCalendarsFromDB();
			while (rscalendars.next()) {
				CheckboxCalendar calendar = new CheckboxCalendar(
						rscalendars.getInt("idCalendar"),
						rscalendars.getString("name"),
						rscalendars.getInt("idCreator"));

				llcalendars.add(calendar);
				JCheckBoxWithObject check = new JCheckBoxWithObject(calendar);
				dlm.addElement(check);
			}

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}

		JScrollPane calscroller = new JScrollPane(calendars);
		calscroller.setBounds(20, 54, 256, 28 * 5);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		getContentPane().add(calscroller);

		JButton btnHinzufgen = new JButton(buttondelete[speak]);
		btnHinzufgen.setBounds(170, 197, 106, 29);
		getContentPane().add(btnHinzufgen);

		ActionListener delete = new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				LinkedList<Integer> iddelete = new LinkedList<Integer>();
				for (int i = 0; i < dlm.size(); i++) {
					JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm.get(i);
					if (temp.isSelected() == true) {
						CheckboxCalendar temp2 = (CheckboxCalendar) temp
								.getObject();
						iddelete.add(temp2.getIdCalendar());
					}

				}

				Statement stat = null;
				try {
					stat = connection.createStatement();
					stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

					for (int j = 0; j < iddelete.size(); j++) {

						stat.executeUpdate("DELETE FROM `sopra-ws12-awesome_fireballs`.`Calendar` WHERE `idCalendar`="
								+ iddelete.get(j)
								+ " AND `idUser`="
								+ Test.iduser + ";");
					}

				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null,
							"Es konnte keine Verbindung zur Datenbank hergestellt werden",
							"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
				}

				((Test) openedfrom).updateLeftPane(true);
				((Test) openedfrom).updateCalendar();
				dispose();
			}
		};

		btnHinzufgen.addActionListener(delete);

		JButton btnAbbrechen = new JButton(buttoncancel[speak]);
		btnAbbrechen.setBounds(61, 197, 106, 29);
		getContentPane().add(btnAbbrechen);

		ActionListener cancle = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		};

		btnAbbrechen.addActionListener(cancle);

	}

	/**
	 * Holt alle Kalender eines Users aus DB
	 * 
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getCalendarsFromDB() throws SQLException {
		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Calendar.* FROM Calendar WHERE idUser = "
						+ Test.iduser + ";");

		return rs;
	}

}
